<template>
  <div class="helpCenter_block">
    <div class="left">
      <div class="content">
        <el-input v-model="searchText" size="medium" type="text" placeholder="搜索帮助类型" />
        <el-button style="width: 100%; margin: 0.2rem 0" type="primary" @click="addItem">+ 帮助类型</el-button>
        <p style="font-size: 15px; font-weight: 700; margin-left: 0.1rem">全部</p>
        <draggable v-model="items">
          <div v-for="(item, index) in items" :key="item.helpTypeId" class="item">
            <span v-if="item" style="cursor: pointer" @click="helpContentList(item.helpTypeId)">{{
              item.helpType
            }}</span>
            <!-- <el-input v-else v-model="item.helpType" /> -->
            <div class="button">
              <el-button type="text" class="btn" icon="el-icon-rank" @click="" />
              <el-button type="text" class="btn" icon="el-icon-edit" @click="editItem(item.helpTypeId)" />
              <el-button type="text" class="btn" icon="el-icon-delete" @click="deleteItem(item.helpTypeId)" />
            </div>
          </div>
        </draggable>
      </div>
    </div>
    <div class="right">
      <div class="top">
        <search-bar
          v-model="searchModel"
          :search-data="searchData"
          :config="searchData"
          style="margin-top: 0; margin-left: -20px; padding-top: 0.2rem"
          @search="handleSearchSubmit"
          @searchReset="handleSearchReset"
        />
      </div>

      <div class="bottom">
        <div class="btn_area" size="medium">
          <el-button type="primary" size="medium" @click="add">+ 帮助</el-button>
          <el-dropdown style="margin-left: 0.1rem" @command="handleCommand">
            <el-button style="width: 110px" size="medium">
              批量操作<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="import">启用</el-dropdown-item>
              <el-dropdown-item command="export">禁用</el-dropdown-item>
              <el-dropdown-item command="delete">删除</el-dropdown-item>
              <!-- <el-dropdown-item command="check">查重</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="" size="medium" style="margin-left: 0.1rem" @click="exportWay">导出</el-button>
        </div>
        <LPTablePage
          ref="tablePage"
          :show-index="true"
          :table-data="tableData"
          :table-column="tableColumn"
          :total="total"
          :current-page="currentPage"
          :selection="true"
          :selectable="selectable"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
          @handleSelectionChange="handleSelectionChange"
        >
          <template slot="isEnabled" slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" />
          </template>
        </LPTablePage>
      </div>
    </div>
    <!-- 编辑/新增 -->
    <base-dialog
      :visible="addVisile"
      :title="(isEdit ? '编辑' : '新增') + '帮助类型'"
      width="700px"
      class="addDictDialog"
      @handleDialogSubmit="handleAddSubmit"
      @handleDialogCancle="handleAddCancle"
    >
      <el-form
        ref="dictForm"
        :model="dictModel"
        :rules="ruleRule"
        label-width="120px"
        class="dictForm"
        label-position="top"
        size="medium"
      >
        <el-row :gutter="50">
          <el-col :span="24">
            <el-form-item style="padding: 0 50px" label="类型名称:" prop="helpType">
              <el-input v-model.trim="dictModel.helpType" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <!-- 取消 -->
    <base-dialog
      :visible="deleteVisile"
      :title="deleteDialogTitle"
      width="440px"
      class="addDictDialog"
      @handleDialogSubmit="handleDeleteSubmit"
      @handleDialogCancle="handleDeleteCancle"
    >
      <el-row :gutter="50">
        <el-col v-if="auditList.length > 1" :span="24">已选择 {{ auditList.length }} 项，确定要取消计划吗？</el-col>
        <el-col v-else :span="24" style="font-size: 15px"> 确定要删除吗？ </el-col>
      </el-row>
    </base-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { validateNumber } from '@/utils/validate'
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
import { logininforList, delLogininfor, cleanLogininfor } from '@/api/system/logs'
import beiGangApi from '@/api/logistics/beigang'

import { addDateRange } from '@/utils/ruoyi'

export default {
  name: 'HelpCenter',
  components: {
    LPTablePage,
    SearchBar,
    baseDialog,
    draggable
  },
  data() {
    const validateNumberF = (rule, value, callback) => {
      if (Number(value) == 0) {
        return callback(new Error('不能为0'))
      }
      if (!validateNumber(value)) {
        return callback(new Error('请输入正确数字'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule, value, callback) => {
      console.log('validateEmpty', value, value instanceof Array)
      if (!(value instanceof Array)) {
        return callback(new Error('必填'))
      }
      if (value instanceof Array && value.length == 0) {
        return callback(new Error('必填'))
      } else {
        callback()
      }
    }
    return {
      ids: [],
      auditList: [],
      searchText: '',
      items: [],
      addVisile: false,
      isEdit: false,
      deleteVisile: false,
      deleteDialogTitle: '删除',
      dictModel: {
        helpType: '',
        helpTypeId: ''
      },
      searchModel: {},
      searchData: [
        { placeholder: '标题', prop: 'title' },
        { placeholder: '内容', prop: 'idCardNumber' },
        {
          prop: 'status',
          type: 'select',
          placeholder: '是否启用',
          options: [
            { label: '启用', value: '0' },
            { label: '关闭', value: '1' }
          ]
        },
        {
          prop: 'search',
          type: 'button',
          policy: ['system.log.query']
        }
      ],
      tableData: [],
      tableColumn: [
        { label: '标题', prop: 'title' },
        { label: '是否启用', prop: 'isEnabled', render: true },
        { label: '操作时间', prop: 'updateTime' },
        { label: '操作人', prop: 'updateTime' },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'button',
          width: 170,
          buttons: [
            {
              label: '查看',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleDetail'
            },
            {
              label: '编辑',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleEdit'
            },
            {
              label: '删除',
              type: 'text',
              color: '#ee3333',
              method: 'handleDelete'
            }
          ]
        }

        //  {
        //     label: "操作",
        //     prop: "action",
        //     type: "button",
        //     hideTooLtip:true,
        //     width:180,
        //     button:[
        //         {
        //             label: "查看",
        //             type: "text",
        //             icon: "el-icon-view",
        //             method:`_detail${this.$options.name}`
        //         },
        //         {
        //             label: "通过",
        //             type: "text",
        //             icon: "el-icon-view",
        //             hide:'isCanTakeAudit',
        //             // hide:'canTakeAudit',
        //             hideValue:[false],
        //             policy:['Crm.CluePoolManage.TakeAudit'],
        //             method:`_auditSuccess${this.$options.name}`
        //         },
        //         {
        //             label: "驳回",
        //             type: "text",
        //             icon: "el-icon-view",
        //             hide:'isCanTakeAudit',
        //             // hide:'canTakeAudit',
        //             hideValue:[false],
        //             policy:['Crm.CluePoolManage.TakeAudit'],
        //             method:`_auditFail${this.$options.name}`
        //         },
        //     ]
        //  }
      ],
      total: 0,
      currentPage: 1,
      selectArr: [],
      allotVisile: false,
      allotModel: {},
      allotRule: {
        responsibleUserId: [
          // { required: true, trigger: "blur", message: "必填" },
          { validator: validateEmpty, required: true, trigger: 'blur' }
        ]
      },
      userOptions: [],
      settingVisile: false,
      ruleModel: {},
      ruleRule: {
        helpType: [{ required: true, trigger: 'blur', message: '必填' }],
        phone: [{ required: true, trigger: 'blur', message: '必填' }],
        idCardNumber: [{ required: true, trigger: 'blur', message: '必填' }],
        drivingLicenseNumber: [{ required: true, trigger: 'blur', message: '必填' }],
        idCardPhotoFace: [{ required: true, trigger: 'change', message: '必填' }],
        idCardPhotoBack: [{ required: true, trigger: 'change', message: '必填' }],
        drivingLicensePhotoMain: [{ required: true, trigger: 'change', message: '必填' }],
        drivingLicensePhotoSecondary: [{ required: true, trigger: 'change', message: '必填' }],
        autoRecycleEnable: [{ required: true, trigger: 'blur', message: '必填' }],
        autoRecycleByNotFollowUpOverDays: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ],

        originalResponsibleUserTakeLimit: [{ required: true, trigger: 'blur', message: '必填' }],
        originalResponsibleUserTakeLimitDays: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ],
        takeLimit: [{ required: true, trigger: 'blur', message: '必填' }],
        takeLimitByEveryDayNumbers: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ]
      },
      detailVisible: false,
      detailId: '',
      openSeaClueId: '',
      status: null,
      isCanTakeAudit: null,
      accountQueryList: []
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter((item) => item.helpType.includes(this.searchText))
    }
  },
  mounted() {
    this.getLogininforList()
    // 详情
    this.$bus.$on('handleDetail', (rows) => {
      this.$router.push({ path: `/logistics/beiGang/helpCenterDetail/${rows.helpId}` })
    })
    // 编辑
    this.$bus.$on('handleEdit', (rows) => {
      this.$router.push({ path: `/logistics/beiGang/helpCenterUpdate/${rows.helpId}` })
    })
    // 删除帮助中心
    this.$bus.$on('handleDelete', (rows) => {
      this.$confirm('确定删除吗', '删除', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        //   console.log('确认');
        // let params = {
        //     ids: this.selectArr.map(item => item.id),
        // }
        beiGangApi.delHelpCenter(rows.helpIdId).then((res) => {
          if (!res.error) {
            this.$message.success('操作成功')
            this.getLogininforList()
            this.$refs.tablePage.clearSelection()
          }
        })
      })
    })
  },
  destroyed() {
    this.$bus.$off('handleDetail')
    this.$bus.$off('handleDelete')
    this.$bus.$off('handleEdit')
  },
  methods: {
    addItem() {
      this.isEdit = false
      this.this.addVisile = true
    },
    editItem(id) {
      this.isEdit = true
      this.addVisile = true
      beiGangApi.gethelpTypeDetail(id).then((res) => {
        this.dictModel = {
          helpType: res.data.helpType,
          helpTypeId: res.data.helpTypeId
        }
      })
    },
    deleteItem(id) {
      this.deleteVisile = true
      this.ids = id
    },
    // 根据帮助类型获取对应列表
    helpContentList(id) {
      const { pageSize } = this.$refs.tablePage
      const params = {
        ...this.searchModel,
        pageSize: pageSize,
        pageNum: this.currentPage,
        helpTypeId: id
      }
      const obj = addDateRange(params, this.searchModel.createTime, 'createTime')
      delete obj.createTime
      const obj1 = addDateRange(obj, this.searchModel.updateTime, 'updateTime')
      delete obj1.updateTime
      beiGangApi.helpCenterList(obj1).then((res) => {
        if (!res.error) {
          this.total = res.total
          this.tableData = res.rows.map((item) => {
            return {
              ...item,
              isEnabled: item.isEnabled + ''
            }
          })
        }
      })
    },
    handleDeleteSubmit() {
      if (this.ids) {
        beiGangApi.delHelpType(this.ids).then((res) => {
          if (res.code == 200) {
            this.$message.success('删除成功')
            this.deleteVisile = false
            this.ids = []
            this.auditList = []
            this.auditParams = this.$options.data().auditParams
            this.getLogininforList()
          }
        })
      }
    },

    handleDeleteCancle() {
      this.deleteVisile = false
    },
    updateOrder() {
      console.log('Items reordered:', this.items)
    },
    handleCommand(val) {
      if (this.selectArr.length == 0) {
        this.$message.warning('请先勾选')
        return
      } else {
        const len = this.selectArr.length
        let title = '启用'
        let content = '确定要启用吗？'

        switch (val) {
          // 启用
          case 'import':
            if (len >= 1) {
              title = '批量启用'
              content = `已选择${len}项，确定要启用吗？`
            }
            this.setEnabled({
              status: 0,
              content,
              title
            })
            break

          case 'export':
            title = '禁用'
            content = '确定要禁用吗？'
            if (len >= 1) {
              title = '批量禁用'
              content = `已选择${len}项，确定要禁用吗？`
            }
            this.setEnabled({
              status: 1,
              content,
              title
            })
            break
          // 删除
          case 'delete':
            if (len >= 1) {
              title = '批量删除'
              content = `已选择${len}项，确定要删除吗？`
            }
            this.setDel()
            break
        }
      }
    },

    // 批量禁启用操作
    setEnabled(obj) {
      console.log(this.selectArr, 'selectArr content')
      const idList = this.selectArr.map((item) => {
        return item.helpId
      })

      this.$confirm(obj.content, obj.title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        const query = {
          idList: idList,
          status: obj.status
        }

        beiGangApi
          .helpBatchUpdateStatus(query)
          .then((res) => {
            if (res.code == 200) {
              // 检查响应码
              this.$message.success('操作成功')
              this.getLogininforList()
              this.$refs.tablePage.clearSelection()
            } else {
              this.$message.error('操作失败')
            }
          })
          .catch((error) => {
            console.error('更新状态时出现错误:', error)
            this.$message.error('操作失败')
          })
      })
    },
    // 批量删除操作
    setDel() {
      if (this.selectArr.length == 0) {
        this.$message.warning('请先勾选')
        return
      }
      let content = '确定删除吗'
      let title = '删除'
      if (this.selectArr.length >= 1) {
        title = '批量删除'
        content = `已选择${this.selectArr.length}项，确定要删除吗？`
      }
      this.$confirm(content, title, {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        const idList = this.selectArr.map((item) => item.helpId)
        beiGangApi.delHelpCenter(idList).then((res) => {
          if (res.code == 200) {
            this.$message.success('操作成功')
            this.getLogininforList()
            this.$refs.tablePage.clearSelection()
          }
        })
      })
    },
    // 导出
    exportWay() {
      this.download(
        'logistics/helpCenter/export',
        {
          ...this.searchData
        },
        `帮助中心_${new Date().getTime()}.xlsx`
      )
    },
    // 新增
    add() {
      this.$router.push({ path: `/logistics/beiGang/helpCenterInsert` })
    },
    // 关联用户帐号模拟查询操作
    getAccountQueryListWay(query) {
      beiGangApi.getAccountQueryList({ phone: query }).then((res) => {
        if (res.code == 200) {
          this.accountQueryList = res.data
        }
      })
    },

    handleAddSubmit() {
      // this.addVisile = false;
      this.$refs.dictForm.validate((valid) => {
        if (valid) {
          if (!this.isEdit) {
            const obj = {
              ...this.dictModel
            }
            beiGangApi.addHelpType(obj).then((res) => {
              if (!res.error) {
                this.dictModel = this.$options.data().dictModel
                this.$message.success('添加帮助类型成功')
                this.addVisile = false
                this.getLogininforList()
              }
            })
          } else {
            const obj = {
              ...this.dictModel
            }
            beiGangApi.updateHelpType(obj).then((res) => {
              if (!res.error) {
                this.$message.success('编辑帮助类型成功')
                this.addVisile = false
                this.getLogininforList()
              }
            })
          }
        } else {
          this.$message.warning('请检查帮助类型')
          return false
        }
      })
    },
    handleAddCancle() {
      this.dictModel = this.$options.data().dictModel
      this.resetForm('dictForm')
      this.addVisile = false
      this.accountQueryList = []
    },
    getLogininforList() {
      // addDateRange

      const { pageSize } = this.$refs.tablePage
      const params = {
        ...this.searchModel,
        pageSize: pageSize,
        pageNum: this.currentPage
      }
      const obj = addDateRange(params, this.searchModel.createTime, 'createTime')
      delete obj.createTime
      const obj1 = addDateRange(obj, this.searchModel.updateTime, 'updateTime')
      delete obj1.updateTime

      console.log('====================================')
      console.log(obj1)
      console.log('====================================')
      // logininforList

      beiGangApi.helpCenterList(obj1).then((res) => {
        if (!res.error) {
          this.total = res.total
          this.tableData = res.rows.map((item) => {
            return {
              ...item,
              isEnabled: item.isEnabled + ''
            }
          })
        }
      })
      beiGangApi.helpTypeList().then((res) => {
        if (!res.error) {
          this.items = res.data.filter((item) => item !== undefined)
        }
      })
    },
    selectable(row, index) {
      return true
      // if (row.status == 0) {
      //     return true
      // } else {
      //     return false
      // }
    },

    handleSearchSubmit() {
      this.currentPage = 1
      this.getLogininforList()
    },
    handleSearchReset() {
      this.currentPage = 1
      this.$refs.tablePage.clearSelection()
      this.getLogininforList()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
      this.getLogininforList()
    },
    handleCurrentChange(v) {
      this.currentPage = v
      this.getLogininforList()
    },
    handleSelectionChange(v) {
      console.log('handleSelectionChange', v)
      this.selectArr = v
    },
    allot() {
      this.$modal
        .confirm('是否确认清空所有登录日志数据项？')
        .then(function () {
          return cleanLogininfor()
        })
        .then(() => {
          this.getLogininforList()
          this.$modal.msgSuccess('清空成功')
        })
        .catch(() => {})
    },

    deleteCustomer() {
      if (this.selectArr.length == 0) {
        this.$message.warning('请先勾选日志')
        return
      }
      this.$confirm('确定删除吗', '删除', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        //   console.log('确认');
        const params = {
          ids: this.selectArr.map((item) => item.infoId)
        }
        delLogininfor(params.ids).then((res) => {
          if (!res.error) {
            this.$message.success('操作成功')
            this.getLogininforList()
            this.$refs.tablePage.clearSelection()
          }
        })
      })
    },
    gethtml(value) {
      if (value == null) {
        return
      }
      var list = value.split(',')
      var resultStr = ''
      list.forEach((item) => {
        if (item.includes('高') || item.includes('重要')) {
          resultStr = resultStr + "<span style='color:#EE3333'>" + item + '</span>,'
        } else {
          resultStr = resultStr + item + ','
        }
      })
      if (resultStr != '') {
        return resultStr.slice(0, -1)
      }
    },

    handleSettingCancle() {
      this.settingVisile = false
    },
    detailClose() {
      this.detailVisible = false
      this.getLogininforList()
    },
    handleAllot() {
      this.allotVisile = true
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.helpCenter_block {
  display: flex;
  .left {
    width: 300px;
    .content {
      padding: 0.3rem;
      .item {
        height: 45px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px;
        span {
          font-size: 15px;
        }
        .btn {
          font-size: 15px;
          margin-left: 5px;
        }
      }
    }
  }
  .right {
    flex: 1;
  }
  // padding: 0 .2rem .2rem;
  .top {
    background-color: #fff;
    padding: 0 0.3rem;
  }

  .bottom {
    .btn_area {
      margin-bottom: 0.2rem;
      margin-left: 0.3rem;
    }

    background-color: #fff;
    margin-top: 0.2rem;
    padding: 0.2rem 0rem;
  }

  .green {
    color: #2cad00;
  }

  .orage {
    color: #ee7533;
  }

  .blue {
    color: #0076ff;
  }

  .red {
    color: #ff3333;
  }
}
.helpCenter_block {
  display: flex;
}

.helpCenter_block .left {
  width: 300px;
}

.helpCenter_block .left .content {
  padding: 0.3rem;
}

.helpCenter_block .left .content .item {
  height: 45px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  transition: background-color 0.3s ease; /* 添加过渡效果 */
}

.helpCenter_block .left .content .item:hover {
  background-color: #f1f7fe; /* 鼠标悬停时更改背景颜色 */
}

.helpCenter_block .left .content .item span {
  font-size: 15px;
}

.helpCenter_block .left .content .item .btn {
  font-size: 15px;
  margin-left: 5px;
  display: none; /* 初始状态隐藏按钮 */
}

.helpCenter_block .left .content .item:hover .btn {
  display: inline-block; /* 鼠标悬停时显示按钮 */
}
</style>
